//
//  YYLComposeViewController.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/4/5.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit
import SVProgressHUD

class YYLComposeViewController: UIViewController {

    //  MARK:------懒加载控件
    //  导航条的标头
    lazy var titleLable: UILabel = {
        let label = UILabel(text: "发微博\n羊羊羊", font: 17, color: UIColor.darkGray)
        if let name = YYLUserAccountViewModel.shareViewModel.userAccount?.name {
            let message:String = "发微博\n" + name
            //获取名字的范围
            let range = (message as NSString).range(of: name)
            
            //创建富文本  把message转成富文本
            let attributStr: NSMutableAttributedString = NSMutableAttributedString(string: message)
            // 设置富文本
            attributStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: UIColor.orange], range: range)
            
            //把富文本赋值给label
            label.attributedText = attributStr
            //设置多行显示
            label.numberOfLines = 0
            label.textAlignment = .center
        } else {
        label.text = "发微博"
        
        }
        label.sizeToFit()
        return label
    }()
    //  导航条的右侧按钮
    lazy var sendBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("发送", for: .normal)
        btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        btn.setTitleColor(UIColor.lightGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.size = CGSize(width: 50, height: 35)

        return btn
    }()
    //  添加自定义TextView
    lazy var textView: YYLTextView = {
        let textView = YYLTextView()
        textView.placeHolder = "在此输入内容~"
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.textColor = UIColor.darkGray
        //textView的可以拖拽
        textView.alwaysBounceVertical = true
        return textView
    }()
    //  添加toolba
    lazy var toolBar:YYLComposeToolBar = YYLComposeToolBar()
    
    //  添加pictureView
    lazy var pictureView: YYLPictureView = YYLPictureView()
    
    //MARK:---------------------------------------------------------------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupNavUI()
    }
    func setupUI() {
        view.backgroundColor = UIColor.white
        //监听键盘的frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChanging(noti: )), name: .UIKeyboardWillChangeFrame, object: nil)
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        //设置代理
        textView.delegate = self
        //布局
        toolBar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(35)
        }
        
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(toolBar.snp.top)
            

        }
        
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-2 * homeCellMargin)
            make.height.equalTo(pictureView.snp.width)
        }
        
        pictureView.picAddCallBack = {[weak self] in
            self?.didSelectedPicture()
        }
        
        toolBar.callBack = {[weak self] (btn: UIButton)->() in
            let type:composeToolBarBtnType = composeToolBarBtnType(rawValue: btn.tag)!
            switch type {
            case .camera:
                print("相机")
                self!.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
            case .add:
                print("+")

            }
        }
    }

    func setupNavUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        self.navigationItem.titleView = titleLable
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        // 设置右侧按钮不可用
        self.navigationItem.rightBarButtonItem?.isEnabled = false
    }
    //取消按钮动作
    @objc private func cancelAction() {
        dismiss(animated: true) {
            //完成后的动作
            }
    }
    //MARK:------发送按钮动作
    @objc private func sendAction() {
        print("发送按钮")

        let access_token = YYLUserAccountViewModel.shareViewModel.accessToken!
        let status = textView.text!
        //发送有图片的微博
        if pictureView.picArray.count > 0 {
            //获取第一张图片
         let pic = pictureView.picArray.first
            YYLNetTools.sharedTools.sendWeiboMessageAndOnePic(access_token: access_token, status: status, pic: pic!, finishCallBack: { (respose, error) in
                if error != nil {
                    print("发送文字微博出错了")
                    SVProgressHUD.showError(withStatus: "发送失败！")
                    return
                }
                //到这里表示发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                //        self.cancelAction()
            })
 
          return
        }
        //  发送文字微博
        YYLNetTools.sharedTools.sendWeiboMessage(access_token: access_token, status: status) { (response, error) in
            if error != nil {
                print("发送文字微博出错了")
                SVProgressHUD.showError(withStatus: "发送失败！")
                return
            }
        //到这里表示发送成功
        SVProgressHUD.showSuccess(withStatus: "发送成功")
//        self.cancelAction()
        }
    }
    
    //监听键盘的frame的改变 键盘的弹出
    @objc private func keyBoardFrameChanging(noti: Notification) {
        let userInfo = noti.userInfo!
        //获取键盘的frame
        let keyBoardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        //获取键盘的动画时长
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        //修改toolbar的底部约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(-(ScreenHeight - keyBoardFrame.origin.y))
        }
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
}
//MARK:------相机按钮点击事件的处理
extension YYLComposeViewController: UIImagePickerControllerDelegate , UINavigationControllerDelegate {
    fileprivate func didSelectedPicture() {
        //在ios10 访问相机和相册需要开启权限
        let imagePickerVC = UIImagePickerController()
        //获取图片要设置代理
        imagePickerVC.delegate = self
        //判断来源
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  真机运行使用相机
            imagePickerVC.sourceType = .camera
        } else {
            //  模拟器运行使用图库
            imagePickerVC.sourceType = .photoLibrary
        }
        
        //扩展
        //判断摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("前置摄像头可用")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("后置摄像头可用")
        }
//        //设置编辑图片 (获取编辑的图片,key是UIImagePickerControllerEditedImage)
//        imagePickerVC.allowsEditing = true
        
        self.present(imagePickerVC, animated: true, completion: nil)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取原始图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let currentImage = scalceImage(scaleWidth: 400, image: image)
        //dismiss   不知道什么意思
        picker.dismiss(animated: true, completion: nil)
        //添加显示的图片
        pictureView.addImage(image: currentImage)
    }

    //根据压缩图片的宽度 来计算图片的大小
    private func scalceImage(scaleWidth: CGFloat, image: UIImage)-> UIImage {
        //根据压缩后的宽度来计算高度
        let scaleHeight = scaleWidth * image.size.height / image.size.width
        //压缩后的大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        //开启图形上下文
        UIGraphicsBeginImageContext(scaleSize)
        //把图片压缩到指定的区域
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        //从图形上下文中获取图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return currentImage!
    }
}

//MARK:------UITextViewDelegate 用代理来根据TextView是否有内容来设置发送按钮的状态
extension YYLComposeViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }

}

